package com.xstudio.pvzreborn.block.machine;

import com.xstudio.pvzreborn.block.BlockNames;
import com.xstudio.pvzreborn.block.entity.BlockEntityPolarCraftingTable;
import com.xstudio.pvzreborn.gui.container.ContainerPolarCraftingTable;
import com.xstudio.pvzreborn.gui.container.PVZMenuProvider;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.material.Material;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.annotation.ParametersAreNonnullByDefault;
import java.util.function.Consumer;

/**
 * @author Bread_NiceCat
 */
@ParametersAreNonnullByDefault
public class BlockPolarCraftingTable extends PVZBlockMachine {

	public BlockPolarCraftingTable() {
        super(Properties.of(Material.STONE).noOcclusion().requiresCorrectToolForDrops().strength(2f, 4f), BlockNames.POLAR_CRAFTING_TABLE);
        this.registerDefaultState(this.stateDefinition.any().setValue(BlockStateProperties.HORIZONTAL_FACING, Direction.NORTH));
		mineableByPickaxe();
		directional();
	}

	@Nullable
	@Override
	public <T extends BlockEntity> BlockEntityTicker<T> getTicker(@NotNull Level pLevel, BlockState pState, BlockEntityType<T> pBlockEntityType) {
		if (pLevel.isClientSide) {
			return getTicker((creator) -> creator.checkWhetherWork(creator.getInputHandler().getAllStacks()));
		}
		return getTicker(BlockEntityPolarCraftingTable::tick);
	}

	@Nullable
	@Override
	public BlockEntity newBlockEntity(@NotNull BlockPos pPos, @NotNull BlockState pState) {
		return new BlockEntityPolarCraftingTable(pPos, pState);
	}

	@Override
	public MenuProvider createMenuProvider(@NotNull Level pLevel, @NotNull BlockPos pPos, @NotNull Player pPlayer) {
		return new PVZMenuProvider<>(guiTransKey, (containerId, inventory) -> new ContainerPolarCraftingTable(containerId, inventory, pPos));
	}
	
	private <T extends BlockEntity> BlockEntityTicker<T> getTicker(Consumer<BlockEntityPolarCraftingTable> consumer) {
		return (level, pos, state, blockEntity) -> {
			if (level.getBlockEntity(pos) instanceof BlockEntityPolarCraftingTable creator) {
				consumer.accept(creator);
			}
		};
	}

}
